package com.wswy.wzcx.ui.adapter;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.SparseArrayCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.ProgressDialogObserver;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.CarColors;
import com.wswy.wzcx.model.license.UserCarInfo;
import com.wswy.wzcx.module.UserDataProvider;
import com.wswy.wzcx.ui.car.result.QueryResultActivity;
import com.wswy.wzcx.ui.hold.ViewHolder;
import com.wswy.wzcx.ui.other.DialogFactory;
import com.wswy.wzcx.widget.shadow.ShadowFrameLayout;
import com.wswy.wzcx.widget.shape.TriangleShape;

import java.util.List;


/**
 * Created by wangduheng26 on 2018/1/19.
 * wangduheng26@gmail.com
 */

public class MyCarCollectAdapter extends BaseAdapter<UserCarInfo, MyCarCollectAdapter.MyCarVh> implements View.OnClickListener,View.OnLongClickListener {
    public MyCarCollectAdapter(List<UserCarInfo> list) {
        super(list);
        setItemOnClickListener(this);
    }

    @Override
    public MyCarVh onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {
        View inflate = inflater.inflate(R.layout.mycat_item, parent, false);
        return new MyCarVh(inflate);
    }

    @Override
    public void onBindViewHolder(MyCarVh holder, UserCarInfo item, int position) {
        holder.bind(item);
        holder.imgRefresh.setOnClickListener(itemListener);
        holder.imgRefresh.setTag(R.id.item_data, item);
        holder.itemView.setTag(R.id.item_position, position);

        CarColors.ColorStyle colorStyle = CarColors.getColorStyle(position);
        int no = position + 1;
        holder.tvSignNo.setText(no >= 10 ? String.valueOf(no) : "0" + no);

        holder.tvSignNo.setTextColor(ContextCompat.getColor(holder.itemView.getContext(), colorStyle.signTextColor));

        holder.shadowFrameLayout.setElevationShadowColor(ContextCompat.getColor(holder.itemView.getContext(),colorStyle.shadowColor));
        holder.contentLayout.setBackgroundResource(colorStyle.bannerBgRes);


        holder.itemView.setTag(R.id.item_data, item);
        holder.itemView.setTag(R.id.item_position, position);
        holder.itemView.setOnLongClickListener(this);

    }

    public void updateItem(final UserCarInfo userCarInfo) {
        if (list != null) {
            int size = list.size();
            int index = -1;
            for (int i = 0; i < size; i++) {
                UserCarInfo info = list.get(i);
                if (info!= null && info.id == userCarInfo.id) {
                    index = i;
                    break;
                }
            }
            if (index != -1) {
                if(!userCarInfo.isError){
                    list.set(index, userCarInfo);
                }
                notifyItemChanged(index);
                final ObjectAnimator animator = animators.get(userCarInfo.id);
                if (animator != null) {
                    animator.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationRepeat(Animator animation) {
                            super.onAnimationRepeat(animation);
                            animator.cancel();
                            animators.remove(userCarInfo.id);
                        }
                    });
                }
            }
        }

    }

    public void deletcItem(int carId){
        if(list != null) {
            int size = list.size();
            int idx = -1;
            for (int i = 0; i < size; i++) {
                if (list.get(i) != null && list.get(i).id == carId) {
                    list.remove(i);
                    idx = i;
                    break;
                }
            }
            if(idx != -1){
                notifyItemRemoved(idx);
            }
        }
    }

    private SparseArrayCompat<ObjectAnimator> animators = new SparseArrayCompat<>();

    @Override
    public void onClick(View v) {
        Context context = v.getContext();
        int id = v.getId();
        if (id == R.id.img_refresh) {
            Object tag = v.getTag(R.id.item_data);
            UserCarInfo userCarInfo = (UserCarInfo) tag;
            if (animators.get(userCarInfo.id) == null) {
                UserDataProvider.get().carFineListRun(userCarInfo.id);
                v.setPivotX(v.getWidth() / 2);
                v.setPivotY(v.getHeight() / 2);
                ObjectAnimator animator = ObjectAnimator.ofFloat(v, View.ROTATION, v.getRotation(), v.getRotation() + 360);
                animator.setInterpolator(new LinearInterpolator());
                animator.setRepeatCount(ObjectAnimator.INFINITE);
                animator.setRepeatMode(ObjectAnimator.RESTART);
                animator.setDuration(2000);
                animator.start();
                animators.put(userCarInfo.id, animator);
            }
        } else {
            final Object tag = v.getTag();
            int pos = (int) v.getTag(R.id.item_position);
            if (tag instanceof UserCarInfo) {
                QueryResultActivity.start(context, ((UserCarInfo) tag),pos);
            }
        }
    }

    @Override
    public boolean onLongClick(final View v) {

        final UserCarInfo userCarInfo = (UserCarInfo) v.getTag(R.id.item_data);

        DialogFactory.create(v.getContext(), "温馨提示", "删除添加车辆", "确定", "取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                delCar(v.getContext(),userCarInfo.id);
            }
        }).show();

        return true;
    }


    private void delCar(Context context, final int carId){
        UserDataProvider.get().deleteCar(carId)
            .subscribe(new ProgressDialogObserver<Object>(context) {
                @Override
                protected void onApiResult(@Nullable Object s) {
                    if(s != null){
                        deletcItem(carId);
                    }
                }

                @Override
                protected void onApiError(@Nullable BaseResult result) {
                    toastErrorMsg(result);
                }
            });
    }

    static class MyCarVh extends ViewHolder {
        View layoutSign;
        TextView tvSignNo;

        //        @BindView(R.id.shadow_view)
//        ShadowView shadowView;

        ShadowFrameLayout shadowFrameLayout;

        TextView tvCarNo;
        TextView tvLastDate;
        TextView tvFineCount;
        TextView tvFinePoints;
        TextView tvFineFee;
        View contentLayout;
        View imgRefresh;

        public MyCarVh(View itemView) {
            super(itemView);

            layoutSign = itemView.findViewById(R.id.layout_sign);
            tvSignNo = itemView.findViewById(R.id.tv_sign_no);
            shadowFrameLayout = itemView.findViewById(R.id.shadow_layout);

            tvCarNo = itemView.findViewById(R.id.tv_car_no);
            tvLastDate = itemView.findViewById(R.id.tv_car_last_query);
            tvFineCount = itemView.findViewById(R.id.tv_fine_count);
            tvFinePoints = itemView.findViewById(R.id.tv_fine_point);
            tvFineFee = itemView.findViewById(R.id.tv_fine_fee);
            contentLayout = itemView.findViewById(R.id.layout_content);
            imgRefresh = itemView.findViewById(R.id.img_refresh);

        }

        public void bind(UserCarInfo item) {
            if (item != null) {
                Context context = AppContext.getContext();
                tvCarNo.setText(item.carNo);
                tvLastDate.setText(context.getString(R.string.last_query, TimeUtils.getFriendlyTimeSpanByNow(item.getLastDate())));
                tvFineCount.setText(context.getString(R.string.fine_count, item.trafficCount));
                tvFinePoints.setText(context.getString(R.string.fine_points, item.totalScore));

                tvFineFee.setText(context.getString(R.string.fine_fee, item.totalFee));

                Drawable background = layoutSign.getBackground();
                if (background == null) {
                    ShapeDrawable background1 = new ShapeDrawable(new TriangleShape());
                    layoutSign.setBackground(background1);
                }


            }
        }
    }
}
